<template>
    <div class="container">
      <div class="main">
        <div class="header">
          <el-button type="primary" @click="add">新建</el-button>
          <el-button type="success" @click="importData">导入</el-button>
          <el-button type="warning" @click="edit">编辑</el-button>
          <el-select v-model="selectedFilter" placeholder="请选择状态" style="width: 200px;">
            <el-option label="启用" value="enabled"></el-option>
            <el-option label="禁用" value="disabled"></el-option>
          </el-select>
          <el-input placeholder="请输入关键字搜索" v-model="searchTable" style="width: 200px;" />
          <el-button type="info" @click="query">查询</el-button>
          <el-button type="info" @click="query">重置</el-button>
        </div>
        <el-table :data="tableData" border class="eltable">
          <el-table-column prop="kq_id" label="序号" width="80"></el-table-column>
          <el-table-column prop="kq_name" label="库区名称"></el-table-column>
          <el-table-column prop="kq_code" label="库区编码"></el-table-column>
          <el-table-column prop="kq_mj" label="面积"></el-table-column>
          <el-table-column prop="ck_name" label="所属仓库"></el-table-column>
          <el-table-column prop="kq_kwsl" label="库位数量"></el-table-column>
          <el-table-column prop="bz" label="备注"></el-table-column>
          <el-table-column prop="kq_zt" label="启用">
            <template #default="{ row }">
              <el-switch v-model="row.kq_zt" active-text="是" inactive-text="否" @change="handleSwitchChange(row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300">
            <template #default="{ row }">
              <el-button type="text" @click="editRow(row)">编辑</el-button>
              <el-button type="text" @click="deleteRow(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
          :total="totalItems" layout="total, prev, pager, next, jumper">
        </el-pagination>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="添加仓区" width="800" :before-close="handleClose">
      <el-form :model="form" class="demo-form-inline" :rules="rules" ref="formRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库区名称" :label-width="formLabelWidth" prop="kq_name">
              <el-input v-model="form.kq_name" placeholder="请输入库区名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="面积" :label-width="formLabelWidth" prop="kq_mj">
              <el-input v-model="form.kq_mj" placeholder="请输入库区面积" type="number" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属仓库" :label-width="formLabelWidth" prop="kq_ssck">
              <el-select v-model="form.kq_ssck" placeholder="请选择所属仓库">
                <el-option v-for="option in warehouseOptions" :key="option.value" :label="option.label"
                  :value="option.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位数量" :label-width="formLabelWidth" prop="kq_kwsl">
              <el-input v-model="form.kq_kwsl" placeholder="请输入库位数量" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" :label-width="formLabelWidth" prop="bz">
              <el-input v-model="form.bz" placeholder="请输入备注" type="textarea" :rows="3"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
  
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="dialogVisible1" title="修改仓区" width="800" :before-close="handleClose">
      <el-form :model="xgform" class="demo-form-inline" :rules="rules" ref="formRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库区名称" :label-width="formLabelWidth" prop="kq_name">
              <el-input v-model="xgform.kq_name" placeholder="请输入库区名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="面积" :label-width="formLabelWidth" prop="kq_mj">
              <el-input v-model="xgform.kq_mj" placeholder="请输入库区面积" type="number" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属仓库" :label-width="formLabelWidth" prop="kq_ssck">
              <el-select v-model="xgform.kq_ssck" placeholder="请选择所属仓库">
                <el-option v-for="option in warehouseOptions" :key="option.value" :label="option.label"
                  :value="option.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库位数量" :label-width="formLabelWidth" prop="kq_kwsl">
              <el-input v-model="xgform.kq_kwsl" placeholder="请输入库位数量" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" :label-width="formLabelWidth" prop="bz">
              <el-input v-model="xgform.bz" placeholder="请输入备注" type="textarea" :rows="3"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
  
      <div class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="upqr">确 定</el-button>
      </div>
    </el-dialog>
  </template>
  
  <script>
  import axios from 'axios';
  import { ref, onMounted } from 'vue';
  
  export default {
    setup() {
      const userId = localStorage.getItem('userId');
      const searchKey = ref('');
      const treeData = ref([]);
      const defaultProps = {
        children: 'children',
        label: 'label',
      };
  
      const tableData = ref([]);
  
      const selectedFilter = ref('');
      const searchTable = ref('');
      const currentPage = ref(1);
      const pageSize = ref(4);
      const totalItems = ref(0);
      const dialogVisible = ref(false);
      const dialogVisible1 = ref(false);
      const form = ref({
        kq_code: '',
        kq_kwsl: '',
        kq_name: '',
        kq_mj: '',
        ck_kx: '',
        kq_ssck: '',
        bz: '',
      });
      const xgform = ref({
        kq_id: '',
        kq_code: '',
        kq_kwsl: '',
        kq_name: '',
        kq_mj: '',
        ck_kx: '',
        kq_ssck: '',
        bz: '',
      });
      const warehouseOptions = ref([]); // 存储下拉框的选项数据
      const formLabelWidth = ref('120px'); // 标签宽度
  
  
      function sx() {
        axios.get('/api/Wbd_kq/GetFYWbd_kq?PageNumber=' + currentPage.value + '&PageSize=' + pageSize.value)
          .then(function (response) {
            console.log(response.data);
            totalItems.value = response.data.zon;
            tableData.value = response.data.wbd_Kqs.map(item => (
              {
                ...item,
                kq_zt: item.kq_zt === 1, // 1 -> true, 0 -> false  
              }
            ))
          }).catch(function (error) {
            console.error('错误:', error);
          })
      }
      sx();
      const add = () => {
        // 添加逻辑  
        dialogVisible.value = true;
      };
      //添加库位下拉框的数据
      const fetchWarehouseOptions = async () => {
        try {
          const response = await axios.get('/api/Wbd_ck/Wbd_Ck');
          //console.log(response.data);
          warehouseOptions.value = response.data.map(item => ({
            label: item.ck_name, // 假设返回的数据中仓库名称字段为 name
            value: item.ck_code    // 假设返回的数据中仓库 ID 字段为 id
          }));
        } catch (error) {
          console.error('获取仓库数据失败:', error);
        }
      };
      const submitForm = async () => {
        const formData = {
          kq_code: form.value.kq_code,
          kq_name: form.value.kq_name,
          kq_mj: form.value.kq_mj,
          kq_ssck: form.value.kq_ssck,
          kq_kwsl: form.value.kq_kwsl,
          bz: form.value.bz,
          create_by: userId,
        };
        console.log(formData);
        try {
          const response = await axios.post('/api/Wbd_kq/AddWbd_Kq', formData);
          if (response.data) {
             ElMessage.error('增加成功');
            sx();
            dialogVisible.value = false;
          }
        } catch (error) {
          console.error('请求错误:', error);
          if (error.response) {
            console.error('服务器返回的错误信息:', error.response.data); // 打印服务器返回的错误信息
          }
        }
      };
      const upqr = async () => {
        const formData = {
          kq_id: xgform.value.kq_id,
          kq_code: xgform.value.kq_code,
          kq_name: xgform.value.kq_name,
          kq_mj: xgform.value.kq_mj,
          kq_ssck: xgform.value.kq_ssck,
          kq_kwsl: xgform.value.kq_kwsl,
          bz: xgform.value.bz,
          update_by: userId,
        }
        console.log(formData);
        try {
          const response = await axios.put('/api/Wbd_kq/UpdateWbd_kq', formData);
          if (response.data) {
             ElMessage.error("修改成功");
            sx();
            dialogVisible1.value = false;
  
          }
        } catch (error) {
          console.error("请求错误:", error);
        }
      }
      const handleSwitchChange=(row)=>{
        const newStatus = row.kq_zt ? 1 : 0;
        axios.put(`/api/Wbd_kq/UpZt?id=${row.kq_id}&zt=${newStatus}`)
          .then(response => {
            console.log('状态更新成功:', response);
  
          })
          .catch(error => {
            // 如果更新失败，你可能需要重置开关的状态  
            /// 还原状态  
          })
      }
      const edit = () => {
        // 编辑逻辑  
      };
  
      const importData = () => {
        // 导入逻辑  
      };
  
      const query = () => {
        // 查询逻辑  
        console.log('Querying with:', searchTable.value);
      };
  
      const editRow = (row) => {
        // 编辑行逻辑  
        console.log('Editing row:', row);
        dialogVisible1.value = true;
        xgform.value = row;
      };
  
      const deleteRow = (row) => {
        // 删除行逻辑  
        console.log('Deleting row:', row);
        if (confirm('确定要删除吗？')) {
          axios.put('/api/Wbd_kq/UpIsDel?id=' + row.kq_id)
          .then(function (response) {
            console.log(response.data);
            if (response.data) {
               ElMessage.error('删除成功');
              sx();
            }
          }).catch(function (error) {
            console.error('错误:', error);
          })
        }
       
      };
  
      const handleCurrentChange = (page) => {
        currentPage.value = page;
        // 分页逻辑  
        console.log('Current page:', page);
        sx();
      };
  
      onMounted(() => {
        fetchWarehouseOptions();
      });
  
      // 确保所有函数都被返回  
      return {
        searchKey,
        treeData,
        defaultProps,
        tableData,
        selectedFilter,
        searchTable,
        currentPage,
        pageSize,
        totalItems,
        add,
        edit,
        importData,
        query,
        editRow,
        deleteRow,
        handleCurrentChange,
        dialogVisible,
        dialogVisible1,
        form,
        xgform,
        formLabelWidth,
        warehouseOptions,
        submitForm,
        userId,
        upqr,
        handleSwitchChange
      };
    },
  };
  </script>
  
  <style>
  .container {
    display: flex;
    gap: 20px;
    height: 95%;
  }
  
  .sidebar {
    height: 100%;
  
  }
  
  .main {
    width: 80%;
    flex: 1;
    height: 100%;
  }
  
  .header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
  }
  
  .eltable {
    height: 95%;
  }
  
  .letree {
    height: 100%;
  }
  </style>